import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Redis } from "ioredis";
import { EnvEnum } from "../enums/env.enum";
import { LoggerService } from "@/common/logger/logger.service";
import { RecordTime } from "../decorators/record-time.decorator";

@Injectable()
export class RedisService
	extends Redis
	implements OnModuleInit, OnModuleDestroy
{
	constructor(
		private readonly configService: ConfigService,
		private readonly logger: LoggerService,
	) {
		super({
			host: configService.get(EnvEnum.REDIS_HOST),
			port: configService.get(EnvEnum.REDIS_PORT),
			password: configService.get(EnvEnum.REDIS_PASSWORD),
			lazyConnect: true, // 延迟连接
		});
		this.logger.setContext(RedisService.name);
	}

	@RecordTime()
	async _get(key: string) {
		return JSON.parse(await this.get(key));
	}

	@RecordTime()
	async _setex(key: string, seconds: number, value: any) {
		await this.setex(key, seconds, JSON.stringify(value)); // 添加实现
	}

	@RecordTime()
	async _set(key: string, value: any) {
		await this.set(key, JSON.stringify(value));
	}

	@RecordTime()
	async _delKeysWithPrefix(prefix: string) {
		const keys = await this.keys(`${prefix}*`);
		if (keys.length === 0) {
			return 0;
		}
		return await this.del(...keys);
	}

	@RecordTime()
	async _delKeysContainStr(str: string) {
		const keys = await this.keys(`*${str}*`);
		if (keys.length === 0) {
			return 0;
		}
		return await this.del(...keys);
	}

	async onModuleInit() {
		try {
			await this.connect();
			//删除所有key
			this.flushall();
			this.logger.log("redis connect success ✅");
			this.logger.log(
				`Connected to Redis: ${this.options.host}:${this.options.port}`,
			);
		} catch (error) {
			this.logger.error("redis connect error ❌", error);
		}
	}
	onModuleDestroy() {
		try {
			this.disconnect(false);
			this.logger.log("redis disconnect success ✅");
		} catch (error) {
			this.logger.error("redis disconnect error ❌", error);
		}
	}
}
